//时间类
class timer {

  //获取当前时间戳 10位
  getTimestamp(ten=true){
    return ten? Date.parse(new Date())/1000 : Date.parse(new Date())
  }

  //获取某个月的总天数
  getAllDays(year, month){
    month = parseInt(month, 10);
    var d= new Date(year, month, 0);
    return d.getDate();
  }
  

  //获取当前时间
  getNowTime(){
    const myDate = new Date();
    const [ fullYear, fullMonth] = [ myDate.getFullYear(), myDate.getMonth()+1];
    const dateList = [ fullYear.toString(),fullMonth.toString() ].join('-')
    return dateList
  }

  //获取当前时间 year month day
  getNowDay(){
    const myDate = new Date();
    const [ fullYear, fullMonth, fullDay] = [ myDate.getFullYear(), myDate.getMonth()+1,myDate.getDate()<10?'0'+myDate.getDate():myDate.getDate()];
    const dateList = [ fullYear.toString(),fullMonth.toString() , fullDay.toString()].join('-')
    return dateList
  }

  //时间转时间戳
  //2018-01-01 01:01:01
  //或者 2018/01/01 01:01:01
  formatTimesTamp(t) {
    return Date.parse(new Date(`${t}`)) || Date.parse(new Date(`${t.replace(/-/g, '/')}`))
  }

  //将10位数时间戳 或者13位数时间戳 
  //转化为 2018-01-01 01:01:01 的时间格式
  formatTime(timestamp){
    timestamp = timestamp.length == 10? timestamp*1000 : timestamp
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(this._formatNumber).join('-') + ' ' + [hour, minute, second].map(this._formatNumber).join(':')
  }

  //查询剩余时间 从现在到 指定时间
  //时间格式 2018-01-01 01:01:01 或 2018/01/01 01:01:01
  restTime( endtime ){
    endtime = endtime.includes('-')? endtime.replace(/-/g,'/') : endtime;
    const overtime = new Date(endtime),
          curtime = new Date().getTime(),
          delta = overtime - curtime;
    if(delta < 0) return 0;
    const days = parseInt( delta / 1000 / 60 / 60 / 24 ), 
          hours = parseInt( delta / 1000 / 60 / 60 - (24  * days) ),
          mins = parseInt( delta / 1000 / 60 - (24 * 60 * days) - (60 * hours) ), 
          second = parseInt( delta / 1000  (24 * 60 * 60 * days) - (60 * 60 * hours) - (60 * mins) );
    
    return days + '-' + [hours, mins, second].map(this._formatNumber).join('-');

  }

  //获取某个时间 之后 N小时的时间
  //nowTime 起始时间的时间戳 10位
  //restTime 剩余的时间 秒数
  //return afterTime 结束的时间
  getCurTime(nowTime = 0,restTime=0) {
    const endtime = nowTime + restTime;
    const afterTime = this.formatTime(endtime);
    return afterTime;
  }

  //私有方法 匹配小于10的数 在前面加'0'
  _formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  }
}

const Timer = new timer();

//导出时间类
export { Timer }